import axios from 'axios'
import { Message } from 'element-ui'
import { ref } from '@/plugins/injectStore'
// import { isProd, isDev } from '@/utils/env'
import { ActionsType } from '@/actions/user'
// import { BASE_URL } from '@/plugins/config'

export function createRequest() {
  const service = axios.create({
    // process.env.baseURL
    // 偷懒一点可以根据 isProd isDev hard code

    baseURL: process.env.BASE_URL,
  })
  // 新歌超管/pwd123456
  service.interceptors.request.use(
    function (config: any) {
      if (ref.store?.getters['user/token']) {
        // JSESSIONID
        config.headers['Access-Token'] = ref.store?.getters['user/token']
      }
      return config
    },
    function (error) {
      // Do something with request error
      console.log(error) // for debug
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    function (response) {
      const res = response.data
      // 后端有可能给字符串
      if (res.status === 200 || res.status === '200') {
        return res.result
      } else if (res.status === 103) {
        // 未登录
        ref.store?.dispatch(ActionsType.logout, res)

        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        Message({
          message: res.message || 'Error',
          type: 'error',
        })

        return Promise.reject(new Error(res.message || 'Error'))
      }
    },
    function (error) {
      console.log('err' + error) // for debug
      Message({
        message: error.message,
        type: 'error',
      })
      return Promise.reject(error)
    }
  )
  return service
}

export const request = createRequest()
